<template>
    <el-dialog custom-class="write-off-payment" v-el-drag-dialog="{ drag: true, full: false, resize: false }"
        :visible="true" :close-on-click-modal="false" @close="closeMd" :title="`付款核销`" width="500px">
        <el-form v-if="isKcbProvideCar" :model="fm.ps" :ref="fm.fname" :label-width="'100px'">
            <el-form-item label="付款类型" prop="payType" required
                :rules="[{ required: true, message: '付款类型不能为空', trigger: 'change' }]">
                <el-radio-group v-model="fm.ps.payType" @change="changePayType">
                    <el-radio :label="1">余额支付</el-radio>
                    <el-radio :label="2">微信扫码支付</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item v-if="fm.ps.payType == 1" key="pay-pass" label="支付密码" prop="payPass" required :rules="[
                { required: true, message: '支付密码不能为空', trigger: 'change' },
                this.$rules.isPayPass()
            ]">
                <el-input prefix-icon="el-icon-lock" show-password placeholder="请输入支付密码" maxlength="6"
                    v-model="fm.ps.payPass">
                </el-input>
            </el-form-item>

            <el-form-item v-if="fm.ps.payType == 2">
                <div class="valid-time">扫码支付<b class="pay-total-money">{{ payTotalMoney }}</b>元，剩余扫码时间{{ qrValidTime }}秒
                </div>
                <div v-show="wxScanPayQRcode" class="wx-pay-qr" ref="wxPayQR"></div>
                <el-image v-show="!wxScanPayQRcode"
                    style="width: 300px; height: 300px;border: 1px solid #ccc;border-radius: 5px;">
                </el-image>
            </el-form-item>
        </el-form>
        <div v-else style="font-size: 16px;font-weight: 600;color: #ff6300;">供车方非客车帮，请联系供车方管理员【手机号：{{ obj.note &&
            obj.note.split('=')[2].split('-')[1] }}】，获取付款方式！</div>

        <div slot="footer" class="dialog-footer" style="display: flex;    justify-content: flex-end;">
            <el-button style="margin-right: 20px;" v-if="fm.ps.payType == 1" type="primary" icon="el-icon-check"
                @click="confirmPay">
                确认支付
            </el-button>
            <div v-if="isKcbProvideCar">
                <el-button v-if="fm.ps.payType == 2" type="danger" icon="el-icon-check" @click="myAlPay">
                    我已支付
                </el-button>

                <el-button type="success" icon="el-icon-close" @click="closeMd">
                    关 闭
                </el-button>
            </div>

        </div>
    </el-dialog>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog';

import * as financeService from '@/api/services/travel/finance.service';

export default {
    name: 'WriteOffPayment',
    directives: { elDragDialog },
    props: { myData: Object },
    data() {
        return {
            // 修改对象数据
            obj: this.myData.obj,

            fm: {// 表单数据对象
                fname: 'writeOffPaymentFm',
                sb: { load: false },
                ps: {
                    // 付款记录id
                    id: this.myData?.obj.id ?? '',
                    // 1-余额支付（默认） 2-微信扫码支付
                    payType: null,
                    // 支付密码
                    payPass: null,
                }
            },

            // 供车方是否是客车帮
            isKcbProvideCar: true,

            // 微信扫码支付二维码地址
            wxScanPayQRcode: '',

            // 支付订单号
            outTradeNo: null,
            // 支付总金额
            payTotalMoney: 0,

            // 二维码图片对象
            qrImgObj: null,
            // 二维码有效时间显示
            qrValidTime: '',
            // 二维码有效时间倒计时定时对象、
            qrTimer: null,

        }
    },
    async created() {
        const that = this, ps = that.fm.ps;

        // 清除一次
        that.clearQrTimer();

        // 支付类型-赋值
        ps.payType = 2;

        // 请求一次支付的数据
        that.changePayType(ps.payType);


        // 是否显示二维码
        if (that.obj) {
            // 付款的供车方不是客车帮，则显示联系方式
            if (that.obj.type == 5 || that.obj.type == 6) {
                if (that.obj.note.split('=')[1] == '8112012054') {
                    that.isKcbProvideCar = true;
                } else {
                    that.isKcbProvideCar = false;
                }

            } else {
                that.isKcbProvideCar = true;
            }
        }
    },
    methods: {
        closeMd() {
            // 清除定时器
            this.clearQrTimer();

            this.$emit("myClick", { state: false });
        },
        // 清除二维码定时器
        clearQrTimer() {
            const that = this;

            that.qrImgObj = null;
            that.qrValidTime = 0;
            // 清除定时器
            if (that.qrTimer) clearInterval(that.qrTimer);
        },
        /**
         * 二维码扫码有效倒计时
         * @param time 传入的总秒数
         */
        validTimeTimer(time = 300) {
            const that = this;

            // 先清除一次定时器
            that.clearQrTimer();

            that.qrValidTime = time;
            that.qrTimer = setInterval(() => {
                if (that.qrValidTime > 0) {
                    that.qrValidTime--;
                } else {
                    that.qrValidTime = 0;
                    // 清除定时器
                    clearInterval(that.qrTimer);

                    // 调起重新生成二维码方法
                    that.changePayType(that.fm.ps.payType);
                }
            }, 1000);
        },
        // 支付方式-改变事件
        changePayType(e) {
            let that = this, U = that.U;

            console.log('点击的值', e);

            if (e == 2) {// 微信支付
                // 请求微信扫码支付数据
                financeService.payApplyOrderByWX({ ids: that.obj?.id }).then(res => {
                    if (res?.code != 1) {
                        U.qerror(res.msg);
                    } else {
                        console.log(res);
                        // 保存-支付编号
                        that.outTradeNo = res.out_trade_no;
                        // 保存-支付总金额
                        that.payTotalMoney = res.total_fee;
                        // 赋值-支付二维码地址
                        that.wxScanPayQRcode = res.code_url;
                        that.qrImgObj = U.str2qrcode(that.$refs.wxPayQR, { text: res.code_url, width: 300, height: 300 }, that.qrImgObj);
                        // 计算倒计时5分钟
                        that.validTimeTimer(300);
                    }
                });
            } else {// 余额支付
                // 清除定时器
                that.clearQrTimer();
            }
        },
        // 我已支付
        myAlPay() {
            const that = this, U = that.U;
            if (!that.isKcbProvideCar) {
                return
            }
            if (!that.outTradeNo) {
                U.qerror('抱歉，您未获取到微信支付数据，请切换支付方式');
            } else {
                // 请求微信扫码支付数据
                financeService.queryWXPayOrder({ outTradeNo: that.outTradeNo }).then(res => {
                    if (res?.code != 1) {
                        U.qerror(res.msg);
                    } else if (res.trade_state == 'NOTPAY') {
                        U.qerror(res.trade_state_desc);
                    } else {
                        console.log(res);
                        U.qsuccess(res.msg);

                        // 关闭弹框
                        that.closeMd();

                        // 调用父组件方法-重新加载数据
                        that.$emit("reloadDg");
                    }
                });
            }
        },

        // 确认支付
        confirmPay() {
            let that = this, U = that.U, fm = that.fm, sb = fm.sb, ps = U.scopy(fm.ps);
            console.log('提交前参数', ps);
            that.$refs[fm.fname].validate((valid) => {
                if (!valid) { return false; } else {
                    let fg = true;

                    // 参数处理
                    if (fg) {

                    }

                    if (fg) {
                        console.log('提交后参数', ps);
                        sb.load = true;
                        financeService.payApplyOrderByBalance(ps).then((res) => {
                            sb.load = false;

                            if (res.code != 1) {
                                U.qerror(res.msg);
                            } else {
                                U.qsuccess(res.msg);

                                // 关闭弹框
                                that.closeMd();

                                // 调用父组件方法-重新加载数据
                                that.$emit("reloadDg");
                            }
                        });

                        setTimeout(() => { sb.load = false; }, 10000);
                    }
                }
            });
        },


    },
}
</script>
<style lang="less" scoped>
.write-off-payment {
    .valid-time {
        padding-bottom: 10px;

        .pay-total-money {
            font-size: 24px;
            color: #f00;
        }

        font-size: 16px;
        font-weight: 600;
        color: #ff6300;
    }

    .wx-pay-qr {
        display: inline-block;

        img {
            border: 1px solid #ccc;
            border-radius: 5px;
            // 设置白色背景色
            background-color: #fff;
            // 利用padding的特性，挤出白边
            padding: 5px;
            box-sizing: border-box;
        }
    }
}
</style>
